package com.zhongpengcheng.controller.common;

import cn.hutool.core.convert.Convert;
import com.zhongpengcheng.blog.advice.GlobalExceptionAdvice;
import com.zhongpengcheng.blog.enums.ResultCodeEnum;
import com.zhongpengcheng.blog.exception.UrlNotFoundException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import static org.springframework.http.HttpStatus.*;
import static javax.servlet.RequestDispatcher.*;

/**
 * 非controller层异常转发处理
 *
 * @author zhongpengcheng
 * @date 2021/08/19 12:21
 **/
@RestController
@RequestMapping
@Slf4j
public class ServletErrorController implements ErrorController {


    @Override
    public String getErrorPath() {
        return null;
    }

    /**
     * servlet异常分发处理
     * @param request http请求
     * @throws Throwable 将servlet中捕获到的异常抛出让全局异常处理器处理
     * @see GlobalExceptionAdvice
     */
    @RequestMapping("${server.error.path:${error.path:/error}}")
    public void dispatchError(HttpServletRequest request) throws Throwable {
        Throwable error = (Throwable)request.getAttribute(ERROR_EXCEPTION);
        if (error != null) {
            handleError(error);
            return;
        }
        handleHtmlError(request);
    }

    /**
     * JSON错误处理
     * @param throwable servlet中抛出的非自定义异常
     */
    private void handleError(Throwable throwable) throws Throwable {
        Throwable cause = throwable.getCause();
        if (throwable instanceof ServletException) {
            throw cause;
        }
        throw throwable;
    }

    /**
     * HTML错误处理
     */
    private void handleHtmlError(HttpServletRequest request) throws Exception {
        HttpStatus statusCode = getStatusCode(request);
        if (statusCode == NOT_FOUND) {
            log.error("请求路径不存在，URL={}, Code={}, IP={}", getUrl(request), statusCode.value(), request.getRemoteAddr());
            throw new UrlNotFoundException(ResultCodeEnum.API_DOES_NOT_EXIST);
        }
        throw new Exception(statusCode.getReasonPhrase());
    }

    private HttpStatus getStatusCode(HttpServletRequest request) {
        Integer code = Convert.toInt(request.getAttribute(ERROR_STATUS_CODE));
        if (code == null) {
            return INTERNAL_SERVER_ERROR;
        }
        return HttpStatus.valueOf(code);
    }

    private String getUrl(HttpServletRequest request) {
        return Convert.toStr(request.getAttribute(ERROR_REQUEST_URI));
    }


}
